<?php

namespace fq\request;

abstract class BaseService
{
	abstract function load($interface, $method);

	abstract function request_interface($data);

	//模板
	public final function play($param_object)
	{
		try {
			$interface = $param_object->getApiInterfaceName();
			$param = $param_object->getApiParas();
			$param_object->check();
			$method = $param_object->getApiMethodName();
			//加载数据
			$this->load($interface, $method);
			//请求接口
			return $this->request_interface($param);
		} catch (\Exception $e) {
			return json_encode(array('code' => 403, 'msg' => '参数错误', 'data' => $e->getMessage()));
		}
	}

	public function curl($url, $method = "GET", $postFields = null, $headers = array())
	{
		$ci = curl_init();
		curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($ci, CURLOPT_FAILONERROR, false);
		curl_setopt($ci, CURLOPT_CONNECTTIMEOUT_MS, 5000);
		curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ci, CURLOPT_TIMEOUT, 5);
		curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
		curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
		curl_setopt($ci, CURLOPT_USERAGENT, "top-sdk-php");
		if ($method == 'POST') {
			curl_setopt($ci, CURLOPT_POST, true);
			if (!empty($postFields)) {
				$postFields = json_encode($postFields);
				curl_setopt($ci, CURLOPT_POSTFIELDS, $postFields);
			}
		}
		curl_setopt($ci, CURLOPT_URL, $url);
		curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ci, CURLINFO_HEADER_OUT, true);
		$response = curl_exec($ci);
		curl_close($ci);
		return $response;
	}

	public function createStrParam($paramArr)
	{
		$strParam = '?';
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
				$strParam .= $key . '=' . urlencode($val) . '&';
			}
		}
		return trim($strParam, '&');
	}


}